/*
 * Copyright (c)  2020,  DataPipeline
 * All rights reserved.
 *
 * Id:PrincipalHandshakeHandler.java   2020-08-19 15:58 wanglijun
 */
package cn.datacare.marmot.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.Map;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2020
 * </p>
 * <p>
 * Company/Department: DataPipeline
 * </p>
 *
 * @author wanglijun
 * @version 1.0
 * @since 2020-08-19 15:58
 */
@Slf4j
@Component
public class PrincipalHandshakeHandler  extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        String username=this.getUsername(request);
        if(StringUtils.isEmpty(username)){
            log.error("未登录系统，禁止登录websocket!");
            return null;
        }
        log.info(" MyDefaultHandshakeHandler login{} " ,username);
        return new AuthPrincipal(username);
    }

    /**
     * 获取用户名
     * @param request
     * @return String
     */
    private String getUsername(ServerHttpRequest request){
        HttpSession httpSession=getSession(request);
        String username=null;
        if(httpSession!=null){
            username=(String)httpSession.getAttribute(Session.SESSION_USERNAME);
        }
        return username;

    }

    /**
     * 获取Session
     * @param httpRequest
     * @return HttpSession
     */
    private  HttpSession getSession(ServerHttpRequest httpRequest){

        if(httpRequest instanceof ServletServerHttpRequest){
            ServletServerHttpRequest  servletServerHttpRequest=(ServletServerHttpRequest)httpRequest;
            return servletServerHttpRequest.getServletRequest().getSession(false);
        }

        return null;
    }

}
